package com.rzl.expense.web.controller.system;

import com.rzl.expense.common.annotation.Log;
import com.rzl.expense.common.constant.UserConstants;
import com.rzl.expense.common.core.controller.BaseController;
import com.rzl.expense.common.core.domain.AjaxResult;
import com.rzl.expense.common.core.domain.entity.SysRegion;
import com.rzl.expense.common.enums.BusinessType;
import com.rzl.expense.common.utils.SecurityUtils;
import com.rzl.expense.common.utils.StringUtils;
import com.rzl.expense.system.service.ISysRegionService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地市信息
 *
 * @author expense
 */
@RestController
@RequestMapping("/system/region")
public class SysRegionController extends BaseController {
    @Autowired
    private ISysRegionService regionService;

    /**
     * 刷新参数缓存
     */
    @Log(title = "参数管理", businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    public AjaxResult refreshCache() {
        regionService.resetConfigCache();
        return success();
    }

    /**
     * 获取地市列表
     */
    @PreAuthorize("@ss.hasPermi('system:region:list')")
    @GetMapping("/list")
    public AjaxResult list(SysRegion region) {
        List<SysRegion> regions = regionService.selectRegionList(region);
        return success(regions);
    }

    /**
     * 查询地市列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:region:list')")
    @GetMapping("/list/exclude/{regionId}")
    public AjaxResult excludeChild(@PathVariable(value = "regionId", required = false) String regionId) {
        List<SysRegion> regions = regionService.selectRegionList(new SysRegion());
        regions.removeIf(d -> d.getRegId() == regionId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), regionId + ""));
        return success(regions);
    }

    /**
     * 根据地市编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:region:query')")
    @GetMapping(value = "/{regionId}")
    public AjaxResult getInfo(@PathVariable String regionId) {
        regionService.checkRegionDataScope(regionId);
        return success(regionService.selectRegionById(regionId));
    }

    /**
     * 新增地市
     */
    @PreAuthorize("@ss.hasPermi('system:region:add')")
    @Log(title = "地市管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRegion region) {
        if (UserConstants.NOT_UNIQUE.equals(regionService.checkRegionNameUnique(region))) {
            return error("新增地市'" + region.getRegName() + "'失败，地市名称已存在");
        }
        region.setCreateBy(getUsername());
        return toAjax(regionService.insertRegion(region));
    }

    /**
     * 修改地市
     */
    @PreAuthorize("@ss.hasPermi('system:region:edit')")
    @Log(title = "地市管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRegion region) {
        String regionId = region.getRegId();
        regionService.checkRegionDataScope(regionId);
        if (UserConstants.NOT_UNIQUE.equals(regionService.checkRegionNameUnique(region))) {
            return error("修改地市'" + region.getRegName() + "'失败，地市名称已存在");
        } else if (region.getRegId().equals(regionId)) {
            return error("修改地市'" + region.getRegName() + "'失败，上级地市不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, region.getStatus()) && regionService.selectNormalChildrenRegionById(regionId) > 0) {
            return error("该地市包含未停用的子地市！");
        }
        region.setUpdateBy(getUsername());
        return toAjax(regionService.updateRegion(region));
    }

    /**
     * 删除地市
     */
    @PreAuthorize("@ss.hasPermi('system:region:remove')")
    @Log(title = "地市管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{regionId}")
    public AjaxResult remove(@PathVariable String regionId) {
        if (regionService.hasChildByRegionId(regionId)) {
            return warn("存在下级地市,不允许删除");
        }
        if (regionService.checkRegionExistUser(regionId)) {
            return warn("地市存在用户,不允许删除");
        }
        regionService.checkRegionDataScope(regionId);
        return toAjax(regionService.deleteRegionById(regionId));
    }

    @GetMapping("/getRegion/{regId}")
    public AjaxResult getRegion(@PathVariable("regId") String regId) {

        return success(regionService.selectRegionList(new SysRegion(regId)));
    }

    /**
     * 获取地市下拉列表
     *
     * @return
     */
    @GetMapping("/regionList")
    public AjaxResult regionList(@RequestParam("regId") String regId) {
        if (StringUtils.isEmpty(regId)) {
            if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                return success(regionService.getRegionList(null));
            } else {
                String regIdParam = SecurityUtils.getLoginUser().getUser().getRegId();
                if ("220000".equals(regIdParam)) {
                    return success(regionService.getRegionList(null));
                } else {
                    boolean hasChild = regionService.hasChildByRegionId(regIdParam);
                    if (hasChild) {
                        return success(regionService.getRegionList(regIdParam));
                    } else {
                        SysRegion sysRegion = regionService.selectRegionById(regIdParam);
                        return success(regionService.getRegionList(sysRegion.getRegId()));
                    }
                }
            }

        }
        return success(regionService.selectChildrenRegionById(regId));
    }

    /**
     * 根据参数键名查询参数值
     */
    @GetMapping(value = "/regionKey/{regionKey}")
    public AjaxResult getRegionKey(@PathVariable String regionKey) {
        return success(regionService.selectRegionByKey(regionKey));
    }
}
